package com.sysu.dinner.action;

import java.io.PrintWriter;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts2.ServletActionContext;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import com.opensymphony.xwork2.ActionSupport;
import com.sysu.dinner.model.User;
import com.sysu.dinner.service.UserService;

@Component("registerAction")
@Scope("prototype")
public class RegisterAction extends ActionSupport{

	private static final long serialVersionUID = 2698254768635097952L;
	
	private String name;
	private String password;
	private String password2;
	private String phone;
	private String email;
	private String address;
	
	private UserService userService;
	
	@Override
	public String execute() throws Exception {
		HttpServletResponse response = ServletActionContext.getResponse();
		response.setContentType("text/javascript;charset=GBK");
		PrintWriter out = response.getWriter();
		
		User user = new User();
		user.setName(name);
		user.setPassword(password);
		user.setPhoneNumber(phone);
		user.setEmail(email);
		user.setAddress(address);
		
		if(userService.isExist(name, phone))
		{
			out.println(1);
			return null;
		}
		
		if(userService.addUser(user)>0)
		{
			HttpSession session = ServletActionContext.getRequest().getSession();;
			session.setAttribute("user", name);
			session.setAttribute("role", "user");
			session.setAttribute("phone", phone);
			out.println(2);
			return null;
		}
		
		out.println(0);
		return null;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public String getPassword2() {
		return password2;
	}

	public void setPassword2(String password2) {
		this.password2 = password2;
	}

	public String getPhone() {
		return phone;
	}

	public void setPhone(String phone) {
		this.phone = phone;
	}

	public String getEmail() {
		return email;
	}

	public void setEmail(String email) {
		this.email = email;
	}

	public String getAddress() {
		return address;
	}

	public void setAddress(String address) {
		this.address = address;
	}

	public static long getSerialversionuid() {
		return serialVersionUID;
	}

	@Resource
	public void setUserService(UserService userService) {
		this.userService = userService;
	}

	public UserService getUserService() {
		return userService;
	}

}
